<?php


namespace plugins\user\api\controller;

use app\exception\ModelException;
use app\model\SysSetting;
use app\service\PhoneCodeService;
use app\service\upload\Upload;
use plugins\user\model\User;
use plugins\user\validate\UserLoginValidate;
use plugins\user\validate\UserValidate;
use think\db\exception\DbException;
use think\exception\ValidateException;
use think\facade\Db;
use think\response\Json;


class UserController extends BaseApiUserController
{
    /**
     * 得到用户的详情
     * @param User $userModel
     */
    public function userInfo(User $userModel)
    {
        $userInfo = $userModel->getInfo(['id' => $this->user['uid'], 'seller_id' => $this->sellerId], "",
            "id,create_time,avatar,nickname,birthday,job,address,avatar,mobile");
        if (!empty($userInfo['data'])) {
            $userInfo['data']['createtime'] = date("Y/m/d");
        }
        return json($userInfo);
    }

    /**
     * 修改用户基本信息
     * @param User $userModel
     * @throws ModelException
     */
    public function editInfo(User $userModel)
    {
        $param = $this->request->only(["avatar" => "", "nickname" => "", "job" => "", "birthday" => "", "address" => ""]);
        try {
            validate(UserValidate::class)->scene("editInfo")->check($param);
        } catch (ValidateException $e) {
            throw new ModelException($e->getMessage(), -1);
        }
        $res = $userModel->edit(['id' => $this->user['uid'], 'seller_id' => $this->sellerId], $param);
        if ($res) {
            return jsonReturn(0, lang('操作成功'));
        }
        return jsonReturn(-1, lang('操作失败'));
    }

    /**
     * 我的收藏
     * @param User $userModel
     * @throws DbException
     */
    public function collectList(User $userModel)
    {
        $category_id = $this->request->param("category_id/d", 0);
        $limit = $this->request->param("limit/d", 10);
        $where[] = ["c.user_id", "=", $this->user['uid']];
        $where[] = ["s.seller_id", "=", $this->sellerId];
        if ($category_id > 0) {
            $where[] = ['s.category_id', "=", $category_id];
        }
        $list = Db::name("user_collection")->alias("c")->join("sub_content s", "s.id = c.article_id")
            ->join("attachment a", "a.id = s.thumbnail")
            ->where($where)
            ->field("s.id,title,thumbnail,s.url,publish_time,author,a.url thumbnail")->paginate($limit)->toArray();
        foreach ($list['data'] as $k => $v) {
            $list['data'][$k]['collection_status'] = 1;
        }
        return jsonReturn(0, lang('查询成功'), $list);
    }

    /**
     * 修改密码
     * @param User $userModel
     * @return Json
     * @throws ModelException
     */
    public function editPwd(User $userModel)
    {
        $param = $this->request->only(['password' => "", "repassword" => ""]);
        try {
            validate(UserLoginValidate::class)->scene("editPwd")->check($param);
        } catch (ValidateException $e) {
            throw new ModelException($e->getMessage(), -1);
        }
        $password = makePassword($param['password']);
        $res = $userModel->edit(['id' => $this->user['uid'], 'seller_id' => $this->sellerId], ['password' => $password]);
        if ($res) {
            return jsonReturn(0, lang('密码修改成功'));
        }
        return jsonReturn(-1, lang('密码修改失败'));
    }

    /**
     * 验证旧密码
     * @param User $userModel
     * @return Json
     * @throws ModelException
     */
    public function checkMobile(User $userModel): Json
    {
        $param = $this->request->only(['mobile' => "", "code" => ""]);
        try {
            validate(UserLoginValidate::class)->scene("codeLogin")->check($param);
        } catch (ValidateException $e) {
            throw  new ModelException($e->getMessage(), -1);
        }

        $smsCode = PhoneCodeService::authCode(['phone'=>$param['mobile'],'code'=>$param['code']]);
        if($smsCode['code']!=0){
            throw new ModelException($smsCode['msg'],$smsCode['code']);
        }

        $info = $userModel->getInfo(['id' => $this->user['uid'], 'seller_id' => $this->sellerId, 'mobile' => $param['mobile']], "",
            "id")['data'];
        if (empty($info)) {
            throw  new ModelException(lang("用户信息不存在"), -2);
        }
        return jsonReturn(0, lang('验证成功'));
    }

    /**
     * 修改号码
     * @param User $userModel
     * @return Json
     * @throws ModelException
     */
    public function editMobile(User $userModel)
    {
        $param = $this->request->only(['mobile' => "", "code" => ""]);
        try {
            validate(UserLoginValidate::class)->scene("codeLogin")->check($param);
        } catch (ValidateException $e) {
            throw  new ModelException($e->getMessage(), -1);
        }
        $smsCode = PhoneCodeService::authCode(['phone' => $param['mobile'], 'code' => $param['code']]);
        if ($smsCode['code'] != 0) {
            throw new ModelException($smsCode['msg'], $smsCode['code']);
        }
        $info = $userModel->getInfo(['id' => $this->user['uid'], 'seller_id' => $this->sellerId], "",
            "id,mobile")['data'];

        if ($info['mobile'] == $param['mobile']) {
            throw new ModelException(lang("新旧号码不能一致"), -3);
        }

        //查询新号码是否绑定
        $info = $userModel->getInfo(['mobile' => $param['mobile'], 'seller_id' => $this->sellerId], "",
            "id")['data'];

        if (!empty($info)) {
            throw new ModelException(lang("号码已存在，请修改号码"), -4);
        }

        $res = $userModel->edit(['id' => $this->user['uid'], 'seller_id' => $this->sellerId], ['mobile' => $param['mobile']]);
        if ($res) {
            return jsonReturn(0, lang('修改成功'));
        }
        return jsonReturn(-1, lang('修改失败'));
    }

    public function search()
    {
        $category_id = $this->request->param("category_id/d", 0); //栏目的id 39,40,41
        $title = $this->request->param("title/s", ""); //关键字
        $where[] = ["s.seller_id", "=", $this->sellerId];
        if ($category_id>0) {
            $where[] = ['s.category_id', "=", $category_id];
        }
        if (!empty($title)) {
            $where[] = ['s.title', "like", "%{$title}%"];
        }
        $list = Db::name("sub_content")->alias("s")->join("attachment a", "a.id = s.thumbnail")
            ->where($where)->field("s.id,title,thumbnail,s.url,publish_time,author,a.url thumbnail")->paginate(10)->toArray();

        $userCollection = [];
        if (!empty($list['data']) && !empty($this->user['uid'])) {
            $articleIds = array_column($list['data'], "id");
            //查询用户的收藏表
            $userCollection = Db::name("user_collection")
                ->where([['user_id', "=", $this->user['uid']], ['article_id', 'in', $articleIds]])
                ->column('id', "article_id");
        }

        foreach ($list['data'] as $k => $v) {
            $list['data'][$k]['collection_status'] = isset($userCollection[$v['id']]) ? 1 : 2;
            $list['data'][$k]['publish_time'] = date("m.d", strtotime($v['publish_time']));
        }
        return jsonReturn(0, lang('成功'), $list);
    }


    /**
     * 收藏/取消收藏
     */
    public function collection()
    {
        $articleId = $this->request->param("id/d", 0);
        if ($articleId <= 0) {
            return jsonReturn(-1,  lang('参数错误'));
        }
        $where = ['user_id' => $this->user['uid'], "article_id" => $articleId];
        $id = Db::name("user_collection")->where($where)->value("id");
        if (empty($id)) {
            $res = Db::name("user_collection")->insert(['user_id' => $this->user['uid'], "article_id" => $articleId]);
            $data = 1;
        } else {
            $data = 2;
            $res = Db::name("user_collection")->where(['id' => $id])->delete();
        }
        if ($res === false) {
            return jsonReturn(-1, lang('操作失败'));
        } else {
            return jsonReturn(0, lang('操作成功'), $data);
        }
    }

    /**
     * 上传
     */
    public function upload()
    {
        if (request()->isPost()) {
            $file = request()->file('file');
            if (empty($file)) {
                return jsonReturn(-2, lang('文件不能为空'));
            }
            $seller_id = $this->sellerId;
            // 查看文件类型
            $fileName = $file->getOriginalName();
            $fileExt = $file->getOriginalExtension();
            $file_type = fileFormat($fileName);
            $type = ['file' => 4, 'image' => 2, 'video' => 3, 'mp3' => 5, 'zip' => 1];
            $fileType = $type[$file_type];
            // 附件大小和类型验证
            // 获取上传配置
            $Settings = new SysSetting();
            $uploadSetting = $Settings->getAllCustomDataModel(['parent_id' => 1, 'group' => 'upload', 'status' => 1], 'id desc', 'id,group,title,value')['data'];
            $uploadSetting = getColumnForKeyArray($uploadSetting, 'title');
            $limitSize = $uploadSetting[$file_type . '_size']['value'] * 1024;     // byte
            $fileSize = $file->getSize();       // 单位byte
            if ($fileSize > $limitSize) {
                return jsonReturn(-1, lang('文件过大，请修改上传限制或者替换小的文件'));
            }
            $extArr = explode(',', $uploadSetting[$file_type . '_ext']['value']);
            if (!in_array($fileExt, $extArr)) {
                return jsonReturn(-2, lang('文件格式错误，请重新上传'));
            }
            // 文件信息提取
            $where = [
                'seller_id' => $seller_id,
                'group' => 'upload',
                'title' => 'storage'
            ];
            $place = new SysSetting();
            $type = $place->getSysSetting($where)['data']->toArray()['value'];

            $upload = new Upload();
            $info = $upload->create($file, $seller_id, $type, $file_type);

            if ($info) {
                $uploadInfo = $upload->getUploadFileInfo();
                if ($uploadInfo['code'] == 0) {
                    $uploadInfo['data']['type'] = $fileType;
                    $uploadInfo['data']['size'] = round($fileSize / 1024, 2);
                    $uploadInfo['data']['mime_type'] = $fileExt;
                }
                return json($uploadInfo);
            } else {
                return jsonReturn(-1, lang('上传失败请重新尝试'));
            }
        }
        return jsonReturn(-3, lang('请求方法错误'));
    }


}